# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2020/9/29 17:16
# @Author     : dqz 
# @Email      : 1513727379@qq.com
# @File       : utils.py
# @Software   : PyCharm
# -----------------------------------------
import sys
import time
from datetime import datetime
from contextlib import contextmanager


def is_valid_datetime(string, format="%Y-%m-%d %H:%M:%S"):
    """校验字符串是不是合法的事件格式"""
    try:
        datetime.strftime(string, format)
    except Exception as e:
        return False
    return True


@contextmanager
def temp_open(filename, mode, encoding="utf-8"):
    f = open(filename, mode, encoding=encoding)
    try:
        yield f
    finally:
        f.close()
        # os.remove(filename)


def fix_object(value):
    """处理value: 只支持python3"""
    if isinstance(value, set):
        value = ','.join(value)

    if isinstance(value, bytes):
        return value.decode("utf-8")
    else:
        return value


def fix_NULL(items):
    """处理NULL"""
    (key, value) = items
    if value is None:
        return '`%s` IS %%s' % key
    else:
        return '`%s`=%%s' % key


def filename():
    runtime = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    if sys.platform.startswith("win"):
        return f"output\\output_{runtime}.txt"
    else:
        return f"output/output_{runtime}.txt"
